import json

import requests

from common.logger import hslogger
from dao.BaseRepository import BaseRepository

gameURL = r"http://yx.haisenyouxi8.com/hsgame/game/queryPage"
pageSize = 50


class HSGameCrawer:
    gameList = []

    def getGameList(self, current, size):
        html = requests.post(url=gameURL, params={"current": current, "size": size})
        records = dict(json.loads(html.content))
        total = int(records.get("total"))
        hslogger.debug("total:{}".format(total))
        gameResults = []
        hslogger.debug(json.dumps(records, ensure_ascii=False))
        for record in records.get("records"):
            gameResults.append(record)
            hslogger.debug(json.dumps(record, ensure_ascii=False))
        return gameResults

    def getTotal(self):
        html = requests.post(url=gameURL, params={"current": 1, "size": "1"})
        records = dict(json.loads(html.content))
        total = int(records.get("total"))
        return total

    def getAllGameList(self):
        total: int = self.getTotal()
        pages = int(total / pageSize) + 1 if total % pageSize > 0 else int(total / pageSize)
        hslogger.debug(pages)
        game_list = []
        for x in range(pages):
            records = self.getGameList(x, pageSize)
            for record in records:
                if record not in game_list:
                    game_list.append(record)
        # hslogger.debug(json.dumps(game_list))
        return game_list


db = BaseRepository(collectionname="hsgame_20200311")
if __name__ == "__main__":

    hscrawr = HSGameCrawer()
    gamelist = hscrawr.getAllGameList()
    for game in gamelist:
        if len(str(game.get("downloadUrl"))) == 0:
            gamelist.remove(game)
        else:
            _, num, _ = db.search_no_page(query={"id": game.get("id")})
            if num == 0:
                db.insert_one(game)

    # hslogger.debug(json.dumps(gamelist, ensure_ascii=False))
    # if len(gamelist) > 0:
    #     hsgamedao = BaseRepository(collectionname="hsgame")
    #     hsgamedao.insert_many(gamelist)

    # hsgamedao = BaseRepository(collectionname="hsgame")
    # result, num, msg = hsgamedao.get_all_no_page()
    # '''
    # for r in list(result):
    #     if len(str(r.get("downloadUrl"))) > 0:
    #         res = requests.get(url=r.get("downloadUrl"))
    #         print(str(res.content))
    #         print("#share_nofound_des" in str(res.content))
    #         time.sleep(1)
    # '''
    # filename = 'for_js.js'
    # with open(filename, 'w') as file_object:
    #     for n in range(num):
    #         file_object.write(' if (result[' + str(n) + '].downloadUrl){')
    #         file_object.write('await page.goto(result[' + str(n) + '].downloadUrl)')
    #         file_object.write(';')
    #         file_object.write(' let r=await page.$("#share_nofound_des")')
    #         file_object.write(';')
    #         file_object.write('if (!r ){')
    #         file_object.write(
    #             'await page.waitForSelector("#shareqr > div.KPDwCE > div.QxJxtg > div > ul.QAfdwP.tvPMvPb > li.fufHyA.yfHIsP > div")')
    #         file_object.write(';')
    #         file_object.write(
    #             'await page.click("#shareqr > div.KPDwCE > div.QxJxtg > div > ul.QAfdwP.tvPMvPb > li.fufHyA.yfHIsP > div")')
    #         file_object.write(';')
    #         file_object.write(
    #             'await page.waitForSelector("#bd-main > div > div.module-share-header > div > div.slide-show-right > div > div > div.x-button-box > a.g-button.g-button-blue")')
    #         file_object.write(';')
    #         file_object.write(
    #             'await page.click("#bd-main > div > div.module-share-header > div > div.slide-show-right > div > div > div.x-button-box > a.g-button.g-button-blue")')
    #         file_object.write(';')
    #         file_object.write(
    #             'await page.waitForSelector("#fileTreeDialog > div.dialog-footer.g-clearfix > a.g-button.g-button-blue-large")')
    #         file_object.write(';')
    #         file_object.write(
    #             'await page.click("#fileTreeDialog > div.dialog-footer.g-clearfix > a.g-button.g-button-blue-large")')
    #         file_object.write(';')
    #         file_object.write('await page.waitForXPath("/html/body/div[5]/div/span[2]/text()")')
    #
    #         file_object.write(';}}')
